package com.hengxinguotong.zhihuichengjian.ui.statistics.attendance;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.github.mikephil.charting.charts.LineChart;
import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.ui.app.BaseFragment;
import com.hengxinguotong.zhihuichengjian.bean.AttendanceFormDataStatistics;
import com.hengxinguotong.zhihuichengjian.bean.AttendanceFormDataStatisticsRes;
import com.hengxinguotong.zhihuichengjian.bean.AttendanceStatistics;
import com.hengxinguotong.zhihuichengjian.bean.AttendanceStatisticsRes;
import com.hengxinguotong.zhihuichengjian.ui.statistics.OnActivityInteractionListener;
import com.hengxinguotong.zhihuichengjian.utils.Constants;
import com.hengxinguotong.zhihuichengjian.utils.LineChartManager;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.lidroid.xutils.http.RequestParams;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * @CopyRight 恒信国通信息科技
 * @Author WuLei
 * @Date 2019/3/28
 * <p>
 * 考勤报表-出勤率
 */

public class AttendanceFormDataAttendanceRateFragment extends BaseFragment implements OnActivityInteractionListener {
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.daily_attendance_line_chart)
    LineChart dailyAttendanceLineChart;
    @BindView(R.id.manager_and_labour_daily_attendance_line_chart)
    LineChart managerAndLabourDailyAttendanceLineChart;
    Unbinder unbinder;

    private LineChartManager dailyAttendanceLineChartManager,
            managerAndLabourDailyAttendanceLineChartManager;
    private String startTime,//开始时间
            endTime;//	结束时间（月报表时，为空）
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case Constants.FORMDATA_COUNT:
                    AttendanceStatistics dailyRateStatistics = (AttendanceStatistics) msg.obj;
                    if (dailyRateStatistics.getxData() == null || dailyRateStatistics.getxData().size() <= 0 ||
                            dailyRateStatistics.getyData() == null || dailyRateStatistics.getyData().size() <= 0) {
                        dailyAttendanceLineChartManager.showNoDataText();
                    } else {
                        List<Drawable> drawables = new ArrayList<>();
                        Drawable redDrawable = getResources().getDrawable(R.drawable.gradient_red);
                        drawables.add(redDrawable);
                        dailyAttendanceLineChartManager.showLineChart(dailyRateStatistics.getxData(), dailyRateStatistics.getyData(),
                                getResources().getColor(R.color.color_F5573F));
//                        dailyAttendanceLineChartManager.setChartFillDrawable(drawables);
                    }
                    break;
                case Constants.FORMDATA_DAILY_COUNT:
                    AttendanceFormDataStatistics managerAndLabourDailyRateFormData = (AttendanceFormDataStatistics) msg.obj;
                    if (managerAndLabourDailyRateFormData.getxData() == null || managerAndLabourDailyRateFormData.getxData().size() <= 0 ||
                            managerAndLabourDailyRateFormData.getyData() == null || managerAndLabourDailyRateFormData.getyData().size() <= 0) {
                        managerAndLabourDailyAttendanceLineChartManager.showNoDataText();
                    } else {
                        List<Drawable> drawables = new ArrayList<>();
                        Drawable redDrawable = getResources().getDrawable(R.drawable.gradient_red);
                        drawables.add(redDrawable);
                        managerAndLabourDailyAttendanceLineChartManager.showLineChart(managerAndLabourDailyRateFormData.getxData(), managerAndLabourDailyRateFormData.getyData().get(0),
                                "管理人员", getResources().getColor(R.color.color_F5573F));
                        Drawable blueDrawable = getResources().getDrawable(R.drawable.gradient_blue);
                        drawables.add(blueDrawable);
                        managerAndLabourDailyAttendanceLineChartManager.addLine(managerAndLabourDailyRateFormData.getyData().get(1),
                                "劳务人员", getResources().getColor(R.color.color_f288ae5));
//                        managerAndLabourDailyAttendanceLineChartManager.setChartFillDrawable(drawables);
                    }
                    break;
            }
        }
    };

    public AttendanceFormDataAttendanceRateFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param startTime Parameter .
     * @param endTime   Parameter .
     * @return A new instance of fragment AttendanceDataStatisticsFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static AttendanceFormDataAttendanceRateFragment newInstance(String startTime, String endTime) {
        AttendanceFormDataAttendanceRateFragment fragment = new AttendanceFormDataAttendanceRateFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, startTime);
        args.putString(ARG_PARAM2, endTime);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            startTime = getArguments().getString(ARG_PARAM1);
            endTime = getArguments().getString(ARG_PARAM2);
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_attendance_form_data_attendance_rate, container, false);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
    }

    private void initView() {
        dailyAttendanceLineChartManager = new LineChartManager(dailyAttendanceLineChart);
        managerAndLabourDailyAttendanceLineChartManager = new LineChartManager(managerAndLabourDailyAttendanceLineChart);
        managerAndLabourDailyAttendanceLineChartManager.setLegend();
    }

    @Override
    public void onLazyLoad() {
        initData();
    }

    private void initData() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                getDailyRateChartData("搜索中…");
                getManagerAndLabourDailyRateChartData("搜索中…");
            }
        }, 500);
    }

    /**
     * 出勤率（每天出勤率）
     *
     * @param alert
     */
    public void getDailyRateChartData(String alert) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("constructionId", SPUtil.getString(getActivity(), "constructionid"));
            jsonObject.put("startTime", startTime);
            jsonObject.put("endTime", endTime);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(alert, getActivity(), "/attendanceReport/getAttendanceByDay/" + SPUtil.getString(getActivity(), "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    AttendanceStatisticsRes res = gson.fromJson(json, AttendanceStatisticsRes.class);
                    if (res.getStatus() == 1) {
                        Message msg = handler.obtainMessage();
                        msg.what = Constants.FORMDATA_COUNT;
                        msg.obj = res.getValue();
                        msg.sendToTarget();
                    } else {
                        showToast(res.getMsg());
                    }
                } else {
                    showToast("系统异常");
                }
            }

            @Override
            public void onFailure(String json) {
                try {
                    JSONObject object = new JSONObject(json);
                    String msg = object.getString("msg");
                    showToast(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    showToast("系统异常");
                }
            }
        });
    }

    /**
     * 出勤率(管理人员与劳务人员每天出勤率)
     *
     * @param alert
     */
    public void getManagerAndLabourDailyRateChartData(String alert) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("constructionId", SPUtil.getString(getActivity(), "constructionid"));
            jsonObject.put("startTime", startTime);
            jsonObject.put("endTime", endTime);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(alert, getActivity(), "/attendanceReport/getManageAndWorkerAttendance/" + SPUtil.getString(getActivity(), "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    AttendanceFormDataStatisticsRes res = gson.fromJson(json, AttendanceFormDataStatisticsRes.class);
                    if (res.getStatus() == 1) {
                        Message msg = handler.obtainMessage();
                        msg.what = Constants.FORMDATA_DAILY_COUNT;
                        msg.obj = res.getValue();
                        msg.sendToTarget();
                    } else {
                        showToast(res.getMsg());
                    }
                } else {
                    showToast("系统异常");
                }
            }

            @Override
            public void onFailure(String json) {
                try {
                    JSONObject object = new JSONObject(json);
                    String msg = object.getString("msg");
                    showToast(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    showToast("系统异常");
                }
            }
        });
    }

    private List<String> getXData(AttendanceFormDataStatistics data) {
        List<String> xData = new ArrayList<>();
        for (int i = 0; i < data.getxData().size(); i++) {
            String x = data.getxData().get(i) + " " + data.getyData().get(1).get(i) + " " + data.getyData().get(0).get(i) + "次";
            xData.add(x);
        }
        return xData;
    }

    private List<Float> getYData(List<String> data) {
        List<Float> yData = new ArrayList<>();
        for (int i = 0; i < data.size(); i++) {
            float y = Float.parseFloat(data.get(i));
            yData.add(y);
        }
        return yData;
    }

    private List<String> getFData(List<Float> data) {
        List<String> yData = new ArrayList<>();
        for (int i = 0; i < data.size(); i++) {
            String y = String.valueOf(data.get(i));
            yData.add(y);
        }
        return yData;
    }

    private List<Integer> getColors2() {
        List<Integer> colors = new ArrayList<>();
        colors.add(getResources().getColor(R.color.color_F5573F));
        colors.add(getResources().getColor(R.color.color_FD9D00));
        return colors;
    }

    private List<Integer> getColors3() {
        List<Integer> colors = new ArrayList<>();
        colors.add(getResources().getColor(R.color.color_EEEEEE));
        colors.add(getResources().getColor(R.color.color_FD9D00));
        colors.add(getResources().getColor(R.color.color_F5573F));
        return colors;
    }

    @Override
    public void OnActivityInteraction(String startTime, String endTime) {
        this.startTime = startTime;
        this.endTime = endTime;
        initData();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
